package com.cwz.core.captcha.core;

import com.cwz.core.captcha.support.CaptchaType;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @program: w-demo
 * @description: 普通验证码生成
 * @author: Wen
 **/
public class Captcha extends AbstractCaptcha {
	@Override
	public void render(OutputStream out) {
		this.drawImage(this.text(), out);
	}

	@Override
	public String toBase64() {
		return this.toBase64("data:image/png;base64,");
	}

	public void drawImage(char[] chars, OutputStream output) {
		BufferedImage img = new BufferedImage(this.width, this.height, 4);
		Graphics2D g = (Graphics2D)img.getGraphics();
		g.setBackground(Color.WHITE);
		g.fillRect(0, 0, this.width, this.height);
		g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		this.drawLine(g);
		this.drawOval(g);
		this.drawBezierLine(g);
		g.setFont(this.getFont());
		FontMetrics fontMetrics = g.getFontMetrics();
		int fw = this.width / chars.length - 2;
		int fm = (fw - (int)fontMetrics.getStringBounds("8", g).getWidth()) / 2;

		for(int i = 0; i < chars.length; ++i) {
			g.setColor(this.color());
			int fh = this.height - (this.height - (int)fontMetrics.getStringBounds(String.valueOf(chars[i]), g).getHeight() >> 1);
			g.drawString(String.valueOf(chars[i]), i * fw + fm, fh);
		}

		g.dispose();

		try {
			ImageIO.write(img, "png", output);
		} catch (IOException var21) {
			var21.printStackTrace();
		}

		try {
			output.flush();
		} catch (IOException var19) {
			var19.printStackTrace();
		} finally {
			try {
				output.close();
			} catch (IOException var18) {
				var18.printStackTrace();
			}

		}

	}

	public Captcha() {
	}

	public Captcha(int width, int height) {
		this();
		this.setWidth(width);
		this.setHeight(height);
	}

	public Captcha(int width, int height, int length) {
		this(width, height);
		this.setLength(length);
	}

	public Captcha(int width, int height, CaptchaType type) {
		this(width, height);
		this.setType(type);
	}

	public Captcha(int width, int height, CaptchaType type, int length) {
		this(width, height, type);
		this.setLength(length);
	}

	public Captcha(int width, int height, CaptchaType type, Font font) {
		this(width, height, type);
		this.setFont(font);
	}

	public Captcha(int width, int height, CaptchaType type, Font font, int length) {
		this(width, height, type, font);
		this.setLength(length);
	}
}
